package sv_tcp

import (
	"venus/common"
	"venus/core"
	"venus/service/sv_tcp/znet"
	"venus/service/sv_tcp/znet/ztcp"
	"venus/util/zlog"
)

type SvTcp struct {
	TcpServer      *ztcp.TcpServer
	TcpBinds       map[uint32]func(*znet.Request) int //处理列表
	TcpBindsSpeedy map[uint32]func(*znet.Request) int //即时处理列表
}

var _Sv *SvTcp

func NewSv(onConnStart func(conn *ztcp.TcpConnection), onConnStop func(conn *ztcp.TcpConnection), fnRegisters ...func()) *SvTcp {
	_Sv = &SvTcp{}
	_Sv.TcpBinds = make(map[uint32]func(*znet.Request) int)
	_Sv.TcpBindsSpeedy = make(map[uint32]func(*znet.Request) int)
	_Sv.TcpServer = ztcp.NewTcpServer(common.TcpHost, common.TcpPort)
	_Sv.TcpServer.OnConnStart = onConnStart
	_Sv.TcpServer.OnConnStop = onConnStop
	_Sv.TcpServer.OnMsgReceive = _Sv.OnMsgReceive
	for _, fn := range fnRegisters {
		fn()
	}
	return _Sv
}

func (sv *SvTcp) Init() {
	zlog.Info(sv.Name() + " Init")

	core.BindMsgExec(core.MsgTypeTcpRequest, sv.Exec)
}

func (sv *SvTcp) Run() {
	zlog.Info(sv.Name() + " Run")

	sv.TcpServer.Start()
}

func (sv *SvTcp) Destroy() {
	zlog.Info(sv.Name() + " Destroy")
}

func (sv *SvTcp) Name() string {
	return "SvTcp"
}

func (sv *SvTcp) Exec(e *core.Msg) {
	request := e.Data.(*znet.Request)
	sv.TcpMsgHandleDo(request)
}
